using System;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using Microsoft.Surface;
using Microsoft.Surface.Presentation;
using Microsoft.Surface.Presentation.Controls;
using CjcAwesomiumWrapper;
using System.Windows.Media.Animation;


namespace Surfium
{

    public partial class MyWindow : ScatterViewItem
    {

        public static readonly RoutedEvent AddedEvent = EventManager.RegisterRoutedEvent(
         "Added", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(MyWindow));

        public event RoutedEventHandler Added
        {
            add { AddHandler(AddedEvent, value); }
            remove { RemoveHandler(AddedEvent, value); }
        }

        public void RaiseAddedEvent()
        {
            RoutedEventArgs newEventArgs = new RoutedEventArgs(MyWindow.AddedEvent);
            RaiseEvent(newEventArgs);
        }


        public double PopUpPositionX
        {

            get { return (double)GetValue(_PopUpPositionX); }
            set { SetValue(_PopUpPositionX, value); }

        }

        public static readonly DependencyProperty _PopUpPositionX =

            DependencyProperty.Register("PopUpPositionX", typeof(double), typeof(MyWindow), new FrameworkPropertyMetadata(0d));
        public double PopUpPositionY
        {

            get { return (double)GetValue(_PopUpPositionY); }
            set { SetValue(_PopUpPositionY, value); }

        }

        public static readonly DependencyProperty _PopUpPositionY =

            DependencyProperty.Register("PopUpPositionY", typeof(double), typeof(MyWindow), new FrameworkPropertyMetadata(0d));

        public static readonly DependencyProperty SlideXChangedProperty = DependencyProperty.Register(
            "slideX",
            typeof(double),
            typeof(MyWindow),
            new PropertyMetadata(OnSlideXChanged));


        private static void OnSlideXChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
        {
            (obj as MyWindow).browser.Offset = (double)args.NewValue;
        }

        private String strDelimValue = Properties.Settings.Default.StringDelim;
        private int thresholdValue = Properties.Settings.Default.Threshold;
        private int selectorSizeValue = Properties.Settings.Default.SelectorSize;

        private const String comJSDelimPropertyName = "strDelim";
        private const String comJSThresholdPropertyName = "threshold";
        private const String comJSSelectorSizePropertyName = "selectorSize";
        private const String comJSEmptyStringPropertyName = "emptyString";

        private const String comJSScollXPropertyName = "scrollX";
        private const String comJSScollYPropertyName = "scrollY";

        private const String comJSObjectName = "SurfiumContainer";
        private const String comJSClickCallbackName = "clickCallback";
        private const String comJSClickImageCallbackName = "clickImageCallback";
        private const String comJSClickFormCallbackName = "clickFormCallback";
        private const String comJSClickSummaryCallback = "clickSummaryCallback";

        private const String comJSDebugInfoCallbackName = "debugInfo";
        private const String comJSReadyCallbackName = "ready";
        private const String comJSBodyResizedCallbackName = "bodyResized";

        private Duration duration;
        private DoubleAnimation slideXAnimation;
        private Storyboard sb;

        private Duration menuFadeOutDuration;
        private DoubleAnimation menuFadeOutAnnimation;
        private Storyboard menuFadeOutSb;

        private Timer timer;


        private bool JsReadyRunning = false;


        public Size ScrollPlaneSize
        {
            set
            {
                scrollViewer.PlaneHeight = value.Height;
                scrollViewer.PlaneWidth = value.Width;
            }

        }



        public void jsCallback(object sender, Cjc.ChromiumBrowser.WebBrowser.CallbackEventArgs e)
        {
            switch (e.CallbackName)
            {
                case comJSBodyResizedCallbackName:
                    if (e.Arguments.Length == 2)
                    {
                        ScrollPlaneSize = new Size(Double.Parse(e.Arguments[0].ToString()), Double.Parse(e.Arguments[1].ToString()));
                    }
                    else
                    {
                        throw new Exception(comJSBodyResizedCallbackName + " takes 2 params was " + e.Arguments.Length);
                    }
                    break;
                case comJSReadyCallbackName:
                    if (e.Arguments.Length == 1)
                    {
                        return;
                    }
                    if (e.Arguments.Length == 2)
                    {
                        Point scrolled = new Point(Double.Parse(e.Arguments[0].ToString()), Double.Parse(e.Arguments[1].ToString()));
                        loadedAndReady(scrolled);
                    }


                    break;
                case comJSClickCallbackName:
                    linkMenu.Items.Clear();

                    if (e.Arguments.Length == 4)
                    {
                        String[] links = (e.Arguments[0] as String).Split(new String[] { strDelimValue }, StringSplitOptions.RemoveEmptyEntries);
                        String[] descs = (e.Arguments[1] as String).Split(new String[] { strDelimValue }, StringSplitOptions.RemoveEmptyEntries);
                        String[] ids = (e.Arguments[2] as String).Split(new String[] { strDelimValue }, StringSplitOptions.RemoveEmptyEntries);
                        String[] dcs = (e.Arguments[3] as String).Split(new String[] { strDelimValue }, StringSplitOptions.RemoveEmptyEntries);

                        if (links.Length != descs.Length || (links.Length != ids.Length)) throw new Exception(comJSClickCallbackName + " Data input error: {" + links.Length + ", " + descs.Length + ", " + ids.Length + ", " + dcs.Length + "}");

                        for (int i = 0; i < links.Length; i++)
                        {
                            linkMenu.Items.Add(new MyMenuItem(links[i], descs[i], Int32.Parse(ids[i]), Int32.Parse(dcs[i]), this, linkMenu));
                        }
                    }
                    else
                    {
                        throw new Exception(comJSClickCallbackName + " takes 4 params was " + e.Arguments.Length);
                    }

                    break;

                case comJSClickImageCallbackName:
                    if (e.Arguments.Length == 6)
                    {
                        String[] links = (e.Arguments[0] as String).Split(new String[] { strDelimValue }, StringSplitOptions.RemoveEmptyEntries);
                        String[] descs = (e.Arguments[1] as String).Split(new String[] { strDelimValue }, StringSplitOptions.RemoveEmptyEntries);
                        String[] alts = (e.Arguments[2] as String).Split(new String[] { strDelimValue }, StringSplitOptions.RemoveEmptyEntries);
                        String[] srcs = (e.Arguments[3] as String).Split(new String[] { strDelimValue }, StringSplitOptions.RemoveEmptyEntries);
                        String[] ids = (e.Arguments[4] as String).Split(new String[] { strDelimValue }, StringSplitOptions.RemoveEmptyEntries);
                        String[] dcs = (e.Arguments[5] as String).Split(new String[] { strDelimValue }, StringSplitOptions.RemoveEmptyEntries);

                        if (links.Length != descs.Length || (links.Length != alts.Length) || (links.Length != srcs.Length) || (links.Length != ids.Length) || (links.Length != dcs.Length)) throw new Exception(comJSClickImageCallbackName + " Data input error: {" + links.Length + ", " + descs.Length + ", " + alts.Length + ", " + srcs.Length + ", " + dcs.Length + "}");

                        for (int i = 0; i < links.Length; i++)
                        {
                            linkMenu.Items.Add(new MyMenuItem(links[i], descs[i], alts[i], srcs[i], Int32.Parse(ids[i]), Int32.Parse(dcs[i]), this, linkMenu));
                        }
                    }
                    else
                    {
                        throw new Exception(comJSClickImageCallbackName + " takes 6 params, was " + e.Arguments.Length);
                    }
                    break;
                case comJSClickFormCallbackName:
                    if (e.Arguments.Length == 4)
                    {
                        String[] ids = (e.Arguments[0] as String).Split(new String[] { strDelimValue }, StringSplitOptions.RemoveEmptyEntries);
                        String[] types = (e.Arguments[1] as String).Split(new String[] { strDelimValue }, StringSplitOptions.RemoveEmptyEntries);
                        String[] labels = (e.Arguments[2] as String).Split(new String[] { strDelimValue }, StringSplitOptions.RemoveEmptyEntries);
                        String[] dcs = (e.Arguments[3] as String).Split(new String[] { strDelimValue }, StringSplitOptions.RemoveEmptyEntries);

                        if (ids.Length != types.Length || (ids.Length != labels.Length) || (ids.Length != dcs.Length))
                            throw new Exception(comJSClickFormCallbackName + " Data input error: {" + ids.Length + ", " + types.Length + ", " + labels.Length + ", " + dcs.Length + ", " + e.Arguments[2] + "}");
                        String empty = Properties.Settings.Default.EmptyStringRepre;
                        for (int i = 0; i < ids.Length; i++)
                        {
                               linkMenu.Items.Add(new MyMenuItem(Int16.Parse(ids[i]), Int16.Parse(types[i]), empty.Equals(labels[i]) ? String.Empty : labels[i], Int32.Parse(dcs[i]), this, linkMenu));

                        }
                    }
                    else
                    {
                        throw new Exception(comJSClickFormCallbackName + " takes 4 params, was " + e.Arguments.Length);
                    }
                    break;

                case comJSClickSummaryCallback:
                    if (e.Arguments.Length == 1)
                    {
                        int count = (int)e.Arguments[0];
                        if (count > 0)
                        {
                            linkMenu.RaiseLoadingSuccessfulEvent();

                        }
                        else
                        {
                            linkMenu.RaiseLoadedEmptyEvent();
                        }
                    }
                    else
                    {
                        throw new Exception(comJSClickSummaryCallback + " takes only 1 params, was " + e.Arguments.Length);
                    }
                    break;

                case comJSDebugInfoCallbackName:
                    if (e.Arguments.Length == 1)
                    {
                    }
                    break;
                default: throw new Exception("Unknown callback from js: " + e.CallbackName);
            }
        }

        private void loadedAndReady(Point scroll)
        {

            url_textbox.Text = browser.Source;

            //scrollViewer.makeDefault();
            if (Properties.Settings.Default.slideEnable)
            {
                pageTransition();
            }
            else
            {
                infoCanvas.Visibility = System.Windows.Visibility.Hidden;
                scrollViewer.IsEnabled = true;
                isLocked = false;
            }

            scrollViewer.ScrollToVerticalOffset(scroll.Y);
            scrollViewer.ScrollToHorizontalOffset(scroll.X);

            JsReadyRunning = true;
        }

        private void pageTransition()
        {

            slideXAnimation.From = 0;
            slideXAnimation.To = browser.ActualWidth;
            browser.imageHold = 1;
            sb.Begin();

            //browser.imageHold = false;
        }



        bool isLocked = false;
        void browser_BeginLoading(object sender, Cjc.ChromiumBrowser.WebBrowser.LoadingEventArgs e)
        {
            if (!IsLoaded) return;

            mpop_hide();
            hideMenu_Animate();

            infoCanvas.Visibility = System.Windows.Visibility.Visible;
            /*locking seq*/
            scrollViewer.IsEnabled = false;
            isLocked = true;
            if (Properties.Settings.Default.slideEnable)
            {
                scatterViewItem.CanScale = false;
                browser.savePixs();
                browser.imageHold = 2;
                //scrollViewer.makeDefault();
            }
            //JsReadyRunning = false;
        }

        private void slide_Completed(object sender, EventArgs e)
        {

            infoCanvas.Visibility = System.Windows.Visibility.Hidden;

            /*unlocking seq*/
            browser.imageHold = 0;
            scatterViewItem.CanScale = true;
            scrollViewer.IsEnabled = true;
            isLocked = false;
        }


        private void hideMenu_Completed(object sender, EventArgs e)
        {
            linkMenuCont.Visibility = System.Windows.Visibility.Hidden;
            linkMenu.Items.Clear();

            if (!touch_detect.IsAnyContactOver && !mpop.IsVisible)
            {
                popupAndMenuUnlock();
            }


        }
        private bool sliderAction = false;

        public void hideMenu_Animate()
        {
            if (sliderAction)
            {
                sliderAction = false;
                return;
            }
            //return;
            menuFadeOutAnnimation.From = 1;
            menuFadeOutAnnimation.To = 0;
            menuFadeOutSb.Begin();

        }

        private void hideMenu_Animate(object sender, RoutedEventArgs e)
        {
            hideMenu_Animate();
        }

        private Thickness menuPosition = new Thickness(0);
        private Point lastClicked = new Point(0, 0);
        private Point lastClickedToBrowser = new Point(0, 0);
        private void ContactHandler(object sender, ContactEventArgs e)
        {
            if (isLocked)
            {
                Storyboard sb = (Storyboard)FindResource("back_sb");
                BeginStoryboard(sb);
                browser.GotoHistoryOffset(-1);
            }


            if (linkMenuCont.IsVisible || !JsReadyRunning || isLocked || !touch_detect.IsAnyContactOver)
            {
                return;
            }
            e.Handled = true;


            lastClickedToBrowser.X = e.GetPosition(browser).X;
            lastClickedToBrowser.Y = e.GetPosition(browser).Y;

            lastClicked.X = e.GetPosition(scrollViewer).X;
            lastClicked.Y = e.GetPosition(scrollViewer).Y;

            linkMenuCont.Visibility = System.Windows.Visibility.Visible;
            linkMenu.IsEnabled = true;
            linkMenu.IsSubmenuOpen = true;

            menuPositionInject();
            menuPositionRefresh();
            if (mpop.IsVisible) mpop_hide();
        }
        private void popupAndMenuLock()
        {
            scrollViewer.Visibility = System.Windows.Visibility.Hidden;
            this.CanScale = false;
        }

        private void popupAndMenuUnlock()
        {
            scrollViewer.Visibility = System.Windows.Visibility.Visible;
            this.CanScale = true;
        }


        private void menuPositionInject()
        {


            linkMenu.RaiseLoadingStartedEvent();
            browser.injectMousePositionAndClick(lastClickedToBrowser);
        }
        private void menuPositionRefresh()
        {
            if (linkMenuCont == null)
            {
                return;
            }
            menuPosition.Left = lastClicked.X - linkMenuCont.Width / 2d;
            menuPosition.Top = lastClicked.Y - linkMenuCont.Height / 2d;
            menuPosition.Right = -linkMenuCont.Width / 2d;
            menuPosition.Bottom = -linkMenuCont.Height / 2d;
            linkMenuCont.Margin = menuPosition;


        }
        private void InitTimer()
        {
            timer = new Timer();
            timer.Elapsed += new ElapsedEventHandler(timeOut_Completed);
            timer.Interval = 500;
        }

        private void TerminateTimer()
        {
            timer.Enabled = false;
            timer.Dispose();
        }
        public MyWindow(String nav)
            : this()
        {

            url_textbox.Text = nav;
            browser.Source = nav;
        }

        public MyWindow()
        {
            InitializeComponent();
            InitAnims();
            InitTimer();
            InitPopUpEventHandlers();

            browser.EnableAsyncRendering = true;

            String jsReady = jsReady = String.Format("var a=document.createElement('script');a.setAttribute('type','text/javascript');a.setAttribute('src','{0}');document.getElementsByTagName('head')[0].appendChild(a);", Properties.Settings.Default.JSUserRef);

            browser.ContactDown += new ContactEventHandler(ContactHandler);
            linkMenu.LoadedEmpty += new RoutedEventHandler(linkMenu_LoadedEmpty);

            browser.Ready += delegate
            {

                scrollViewer.ScrollChanged += new ScrollChangedEventHandler(scrollViewer_ScrollChanged);

                scrollViewer.Back += new RoutedEventHandler(scrollViewer_Back);
                scrollViewer.Forward += new RoutedEventHandler(scrollViewer_Forward);
                browser.CreateObject(comJSObjectName);

                browser.SetObjectProperty(comJSObjectName, comJSDelimPropertyName, new JSValue(strDelimValue));
                browser.SetObjectProperty(comJSObjectName, comJSThresholdPropertyName, new JSValue(thresholdValue));
                browser.SetObjectProperty(comJSObjectName, comJSSelectorSizePropertyName, new JSValue(selectorSizeValue / 2));
                browser.SetObjectProperty(comJSObjectName, comJSEmptyStringPropertyName, new JSValue(Properties.Settings.Default.EmptyStringRepre));

                browser.SetObjectCallback(comJSObjectName, comJSClickCallbackName);
                browser.SetObjectCallback(comJSObjectName, comJSClickImageCallbackName);
                browser.SetObjectCallback(comJSObjectName, comJSClickFormCallbackName);
                browser.SetObjectCallback(comJSObjectName, comJSClickSummaryCallback);

                browser.SetObjectCallback(comJSObjectName, comJSDebugInfoCallbackName);
                browser.SetObjectCallback(comJSObjectName, comJSReadyCallbackName);
                browser.SetObjectCallback(comJSObjectName, comJSBodyResizedCallbackName);

                browser.Callback += new EventHandler<Cjc.ChromiumBrowser.WebBrowser.CallbackEventArgs>(jsCallback);
                browser.BeginLoading += new EventHandler<Cjc.ChromiumBrowser.WebBrowser.LoadingEventArgs>(browser_BeginLoading);

                browser.FinishLoading += delegate
              {
                  browser.ExecuteJavascript(jsReady, "");
              };
            };

            url_textbox.Text = Properties.Settings.Default.StartupUrl;
            browser.Source = Properties.Settings.Default.StartupUrl;

        }





        private void InitPopUpEventHandlers()
        {
            mpop.TextChanged += new RoutedEventHandler(mpop_TextChanged);
            mpop.InputText.LostFocus += new RoutedEventHandler(mpop_LostFocus);
        }


        void linkMenu_LoadedEmpty(object sender, RoutedEventArgs e)
        {
            timer.Start();

        }
        public delegate void timer_delegate();

        void timeOut_Completed(object sender, EventArgs e)
        {

            sliderAction = false;
            timer.Stop();
            Dispatcher.BeginInvoke(new timer_delegate(hideMenu_Animate), null);

        }

        private void InitAnims()
        {
            duration = new Duration(TimeSpan.FromSeconds(Properties.Settings.Default.PageTransitionInSec));
            slideXAnimation = new DoubleAnimation();
            sb = new Storyboard();
            sb.Completed += new EventHandler(slide_Completed);
            slideXAnimation.Duration = duration;
            slideXAnimation.FillBehavior = FillBehavior.Stop;


            sb.AccelerationRatio = 0.2d;
            sb.DecelerationRatio = 0.3d;
            sb.Duration = duration;
            sb.Children.Add(slideXAnimation);


            Storyboard.SetTarget(slideXAnimation, this);

            Storyboard.SetTargetProperty(slideXAnimation, new PropertyPath("slideX"));

            this.Resources.Add("slideTransition", sb);

            /* --------*/
            menuFadeOutDuration = new Duration(TimeSpan.FromSeconds(0.5));
            menuFadeOutAnnimation = new DoubleAnimation();
            menuFadeOutSb = new Storyboard();
            menuFadeOutSb.Completed += new EventHandler(hideMenu_Completed);

            menuFadeOutAnnimation.Duration = menuFadeOutDuration;

            menuFadeOutAnnimation.FillBehavior = FillBehavior.Stop;

            menuFadeOutSb.AccelerationRatio = 0.1d;
            menuFadeOutSb.DecelerationRatio = 0.2d;
            menuFadeOutSb.Duration = menuFadeOutDuration;
            menuFadeOutSb.Children.Add(menuFadeOutAnnimation);

            Storyboard.SetTarget(menuFadeOutAnnimation, linkMenuCont);
            Storyboard.SetTargetProperty(menuFadeOutAnnimation, new PropertyPath("Opacity"));
            this.Resources.Add("menuFadeOut", sb);


        }


        void scrollViewer_Back(object sender, RoutedEventArgs e)
        {
            Storyboard sb = (Storyboard)FindResource("back_sb");
            BeginStoryboard(sb);

            browser.forward = false;
            browser.GotoHistoryOffset(-1);


        }
        void scrollViewer_Forward(object sender, RoutedEventArgs e)
        {
            Storyboard sb = (Storyboard)FindResource("forward_sb");
            BeginStoryboard(sb);

            browser.forward = true;
            browser.GotoHistoryOffset(1);


        }


        public String Source
        {
            get
            {
                return browser.Source;
            }
            set
            {
                browser.Source = value;
            }
        }


        public void navigate(string url)
        {
            browser.forward = true;
            try
            {
                try
                {
                    Uri u = new Uri(url);
                }
                catch (UriFormatException)
                {
                    Uri uri = new Uri(Source);
                    url = new Uri(uri, url).AbsoluteUri;
                }
            }
            catch (Exception)
            {
                url = "about:blank";
            }
            browser.Navigate(url);

        }

        void scrollViewer_ScrollChanged(object sender, ScrollChangedEventArgs e)
        {

            if (JsReadyRunning)
            {
                browser.SetObjectProperty(comJSObjectName, comJSScollYPropertyName, new JSValue((Int32)(e.VerticalOffset / scrollViewer.Scale)));
                browser.SetObjectProperty(comJSObjectName, comJSScollXPropertyName, new JSValue((Int32)(e.HorizontalOffset / scrollViewer.Scale)));
            }


        }

        private void touch_detect_ContactDown(object sender, ContactEventArgs e)
        {

            e.Handled = true;

            popupAndMenuLock();
            touch_detect_border.Tag = "contact";
        }

        private void touch_detect_ContactLeave(object sender, ContactEventArgs e)
        {
            e.Handled = true;
            if (!touch_detect.IsAnyContactOver)
            {
                touch_detect_border.Tag = "";
                if (!linkMenuCont.IsVisible && !mpop.IsVisible)
                    popupAndMenuUnlock();

            }
        }

        private void URL_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {

            if (e.Key == System.Windows.Input.Key.Enter)
            {
                string text = (sender as SurfaceTextBox).Text;

                if (text.Length == 0) return;
                try
                {
                    browser.Navigate(new Uri(text).AbsoluteUri);
                }
                catch (UriFormatException)
                {
                    try
                    {
                        browser.Navigate(new Uri("http://" + text).AbsoluteUri);
                    }
                    catch (UriFormatException)
                    {
                        browser.Navigate("http://www.bing.com/search?q=" + text);

                    }
                }
            }
        }



        public void BlinkLink(int Id)
        {
            String jsCall = String.Format("blink(currentActives[{0}])", Id);
            browser.ExecuteJavascript(jsCall, "");

        }

        private void linkMenuContSizeSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            menuPositionRefresh();
        }

        private void linkMenuContSizeSlider_LostContactCapture(object sender, ContactEventArgs e)
        {
            sliderAction = true;

            browser.SetObjectProperty(comJSObjectName, comJSSelectorSizePropertyName, new JSValue((sender as SurfaceSlider).Value / 2));
            menuPositionInject();

        }

        private void LoadedEmpty_Storyboard_Completed(object sender, EventArgs e)
        {
            hideMenu_Animate(null, null);
        }


        internal void injectInput(int id, FormType type, string label)
        {
            mpop.set(id, type, label);
            PopUpPositionX = lastClicked.X;
            PopUpPositionY = lastClicked.Y;

            mpop.Visibility = System.Windows.Visibility.Visible;
            mpop.focus();

        }

        void mpop_LostFocus(object sender, RoutedEventArgs e)
        {
            mpop_hide();
        }

        void mpop_hide()
        {
            mpop.Visibility = System.Windows.Visibility.Hidden;
            if (!touch_detect.IsAnyContactOver)
            {
                popupAndMenuUnlock();

            }
        }

        void mpop_TextChanged(object sender, RoutedEventArgs e)
        {

            String jsCall = String.Format("insetTextIntoInput(\"{0}\",{1})", mpop.InputText.Text, mpop.ComponentId);
            browser.ExecuteJavascript(jsCall, "");


        }



        internal void emulateClick(int id)
        {
            browser.forward = true;
            String jsCall = String.Format("emulateClick({0})", id);
            browser.ExecuteJavascript(jsCall, "");
        }

        private void scatterViewItem_DragEnter(object sender, SurfaceDragDropEventArgs e)
        {
            MyDragCursor mdc = e.Cursor.Visual as MyDragCursor;
            if (mdc.Source == this)
            {
                mdc.RaiseDroppableThisEnterEvent();

            }
            else
            {
                mdc.RaiseDroppableOtherEnterEvent();
            }
            e.Handled = true;
        }

        private void scatterViewItem_DragLeave(object sender, SurfaceDragDropEventArgs e)
        {

            MyDragCursor mdc = e.Cursor.Visual as MyDragCursor;
            if (mdc.Source == this)
            {
                mdc.RaiseDroppableThisLeaveEvent();

            }
            else
            {
                mdc.RaiseDroppableOtherLeaveEvent();
            }
            e.Handled = true;
        }

        private void scatterViewItem_Drop(object sender, SurfaceDragDropEventArgs e)
        {
            MyDragCursor mdc = e.Cursor.Visual as MyDragCursor;
            navigate(mdc.Link);
            e.Handled = true;
        }

        private void ClosingSB_Completed(object sender, EventArgs e)
        {

            (this.Parent as ScatterView).Items.Remove(this);
           
            browser.Dispose();

        }


    }
}